package com.home.rhclient;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

import android.content.Context;
import android.util.Log;

import com.home.rhtester.R;

public class Encryptor {

	
	private PrivateKey privateKey;
	private PublicKey publicKey;
	private Base64 base64;
	
	public Encryptor(Context context) throws Exception {
		
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		publicKey=readPublicKey(context,keyFactory);
		privateKey=readPrivateKey(context,keyFactory);

	    Log.v("Encryptor", "Public: "+publicKey.getEncoded()+" Private:  "+privateKey.getEncoded());
		Log.v("Encryptor", "Public: "+publicKey.getFormat()+" Private:  "+privateKey.getFormat());
		
	}
	
	

	private PrivateKey readPrivateKey(Context context,KeyFactory keyFactory) throws IOException, GeneralSecurityException {
		PKCS8EncodedKeySpec keySpecs =new PKCS8EncodedKeySpec(readKeySpecsFromFile(context,R.raw.privk));
		PrivateKey returnKey=keyFactory.generatePrivate(keySpecs);
		return returnKey;
	}

	private PublicKey readPublicKey(Context context,KeyFactory keyFactory) throws InvalidKeySpecException, IOException {
		X509EncodedKeySpec keySpecs = new X509EncodedKeySpec(readKeySpecsFromFile(context,R.raw.pubk));
		PublicKey returnKey=keyFactory.generatePublic(keySpecs);
		return returnKey;
	}
	private byte[] readKeySpecsFromFile(Context context,int resourceID)
			throws IOException {
			InputStream in=context.getResources().openRawResource(resourceID);
			BufferedInputStream buffer=new BufferedInputStream(in);
			byte[] key=new byte[buffer.available()];
			buffer.read(key);
			buffer.close();
			return key;
		}



	public String rsaEncrypt(String data) throws Exception {
		
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] byteData = data.getBytes("UTF-8");
		byte[] encryptedData = cipher.doFinal(byteData);
		//Log.v("rsaEncrypt","ByteData: "+new String(encryptedData,"UTF-8"));
		byte[] endodedString=Base64.encodeBase64(encryptedData);
		return new String(endodedString,"UTF-8");
	}

	public String rsaDecrypt(String data) throws Exception {
	
		byte[] byteData=Base64.decodeBase64(data);
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		//byte[] byteData = data.getBytes();
		byte[] encryptedData = cipher.doFinal(byteData);
		return new String(encryptedData);
	}

}
